// Package __DFS 200_island_nums
// @Title __DFS
// @Description
// @Author  == 琳琳也叫王木木 ==  2021/9/6 18:46
// @Create  2021/9/6 18:46
package __DFS

func NumIslands(grid [][]byte) int {
	if grid == nil || grid[0] == nil {
		return 0
	}
	N := len(grid)    // 行号
	M := len(grid[0]) // 列号
	ans := 0
	for i := 0; i < N; i++ {
		for j := 0; j < M; j++ {
			if grid[i][j] == 1 {
				ans++
				infect(grid, i, j, N, M)
			}
		}
	}
	return ans
}

// 感染岛屿
func infect(grid [][]byte, i, j, n, m int) {
	if i < 0 || j < 0 || i >= n || j >= m || grid[i][j] != 1 {
		return
	}
	// 先感染，避免死循环
	grid[i][j] = 2
	// 感染他的上下左右四个邻居
	infect(grid, i-1, j, n, m)
	infect(grid, i, j-1, n, m)
	infect(grid, i+1, j, n, m)
	infect(grid, i, j+1, n, m)
}
